package com.liu.qqRobot.myself.handler;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ZipUtil;
import com.liu.common.content.RedisKeyInterface;
import com.liu.common.utils.QQClientUtils;
import com.liu.qqRobot.event.entity.dto.EventReportingDTO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

@Slf4j
@Component
public class JmHandler {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 处理事件
     * @param data 信息内容
     * @param groupId 群号
     */
    public void handler(EventReportingDTO.Message.Data data, Long groupId) {
        Boolean hasKey = redisTemplate.hasKey(RedisKeyInterface.JM_LOCK);
        if (Boolean.TRUE.equals(hasKey)) {
            log.error("jm正在执行请稍后再试！");
            return;
        }
        try {
            redisTemplate.opsForValue().set(RedisKeyInterface.JM_LOCK, "1");
            String jmId = data.getText().replace("jm ", "");
            String property = System.getProperty("user.dir");
            ProcessBuilder pb = new ProcessBuilder("python", "src\\main\\resources\\jm\\asd.py", jmId, property + "\\src\\main\\resources\\jm\\option.yml");
            Process process = pb.start();
            String line;
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
            while ((line = stdInput.readLine()) != null) {
                log.info("标准输出：" + line);
            }
            BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            while ((line = stdError.readLine()) != null) {
                log.error("报错输出：" + line);
            }
            process.waitFor();
            int count = 0;
            while (true) {
                File file = new File("F:\\warframe\\jm\\pdf");
                if (!file.exists()) {
                    count++;
                    ThreadUtil.sleep(1000);
                    if (count >= 10) {
                        break;
                    }
                } else {
                    break;
                }
            }
            ZipUtil.zip("F:\\warframe\\jm\\pdf");
            QQClientUtils.uploadGroupFile(groupId, jmId + ".zip", "F:\\warframe\\jm\\pdf.zip");
            ThreadUtil.sleep(1000);
            FileUtil.del("F:\\warframe\\jm");
        } catch (Exception e) {
            log.error("获取jmPDF失败， {}", e.getMessage(), e);
        } finally {
            redisTemplate.delete(RedisKeyInterface.JM_LOCK);
        }
    }
}
